<script setup>
import patentService from '@/api/modules/patent.js'
import ApplicationFeeDialog from '@/components/ApplicationFeeDialog/ApplicationFeeDialog.vue'
import AuthModal from '@/components/AuthModal/AuthModal.vue'
import BaseDialog from '@/components/BaseDialog/BaseDialog.vue'
import SvgIcon from '@/components/SvgIcon/SvgIcon.vue'
import useSettingsStore from '@/store/modules/settings.js'
import useUserStore from '@/store/modules/user.js'
import { getToken } from '@/utils/auth.js'
import { nowDateInfo } from '@/utils/day.js'
import log from '@/utils/log.js'
import messageHelper from '@/utils/messageHelper.js'
import { ElLoading, ElMessageBox } from 'element-plus'
import { isEmpty } from 'lodash-es'

const queryCount = ref(0)
const searchVal = ref('')
const dialogVisible = ref(false)
const queryStatusType = ref('')
const queryStatusVisible = ref(false)
const authVisible = ref(false)

const applicationData = ref({})
const feeData = ref({})
const queryMessage = computed(() => {
  if (queryStatusType.value === 'error') {
    return `当前专利号 ${searchVal.value} 未查询到数据！`
  }
  return `当前专利号 ${searchVal.value} 已查询到数据，点击查看详情`
})

const token = getToken()

const userStore = useUserStore()
const settingStore = useSettingsStore()
const showPopup = ref(false)
const qrCodeUrl = ref('https://via.placeholder.com/100') // 这里替换成真实的二维码图片地址

const feeVisible = ref(false)

const title = import.meta.env.VITE_APP_TITLE
onMounted(() => {
  if (token) {
    handleGetUserQueryContent()
  }
})

async function handleQuery() {
  if (!token) {
    messageHelper.message.warning('您尚未登录，请登录后再进行操作！')
    authVisible.value = true
    return
  }
  if (queryCount.value === 0) {
    return ElMessageBox.confirm('当前账号的查询次数已用完，请联系客服 联系方式 18652920043', '系统提示', {
      showCancelButton: false,
      type: 'warning',
    })
  }
  const loading = ElLoading.service({
    text: '数据查询中...',
    customClass: 'query-loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  try {
    const res = await patentService.patentQueryDetail({ applicationNumber: searchVal.value })
    const { detailVo = {}, feeDetailVo = {} } = res?.data || {}
    const hasData = !isEmpty(detailVo) || !isEmpty(feeDetailVo)
    if (hasData) {
      queryStatusType.value = 'success'
      applicationData.value = detailVo
      feeData.value = feeDetailVo
    }
    else {
      queryStatusType.value = 'error'
    }
    queryStatusVisible.value = true
    await handleGetUserQueryContent()
  }
  catch (error) {
    log.error(error)
  }
  finally {
    loading?.close()
  }
}

async function handleGetUserQueryContent() {
  try {
    const res = await patentService.getQueryCount()
    queryCount.value = res.data ?? 0
  }
  catch (error) {
    log.error('查询用户剩余次数失败', error)
    queryCount.value = 0
  }
}

function resetQueryState() {
  dialogVisible.value = false
  queryStatusType.value = ''
  queryStatusVisible.value = false
}

function handleViewFeeDetail() {
  queryStatusVisible.value = false
  feeVisible.value = true
}

function handleCommand(command) {
  switch (command) {
    case 'logout':
      messageHelper.confirm('确认退出登录吗？').then(async (res) => {
        await userStore.logOut()
        await settingStore.reloadPage()
        messageHelper.message.success('退出登录成功！')
      })
      break
  }
}
</script>

<template>
  <div class="flex min-h-screen flex-col">
    <header class="sticky top-0 z-40 w-full border-b bg-background">
      <div class="container flex h-16 items-center justify-between">
        <div class="flex items-center gap-2">
          <router-link to="/" class="flex items-center gap-2">
            <img
              alt="logo" width="32" height="32" decoding="async" data-nimg="1" class="rounded"
              src="@/assets/images/logo.png"
            >
            <span class="text-xl font-bold">
              {{ title }}
            </span>
          </router-link>
        </div>
        <button class="block md:hidden">
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-menu"><line x1="4" x2="20" y1="12" y2="12" /><line x1="4" x2="20" y1="6" y2="6" /><line x1="4" x2="20" y1="18" y2="18" /></svg>
        </button>
        <div class="hidden md:flex items-center gap-4">
          <div v-if="token">
            <el-dropdown trigger="click" @command="handleCommand">
              <div class="avatar-wrapper h-9 flex-center gap-1 px-2">
                <el-avatar :src="userStore.userAvatar" :size="33" />
                <span class="ml-1 text-base">
                  {{ userStore.userInfo.userName }}
                  <SvgIcon name="ep:caret-bottom" class="" />
                </span>
              </div>
              <template #dropdown>
                <el-dropdown-menu class="!w-45">
                  <div class="p-3 flex">
                    <el-avatar :src="userStore.userAvatar" :size="40" shape="square" />
                    <div class="ml-3">
                      <div class="text-base text-[var(--el-text-color-primary)]">
                        {{ userStore.userInfo.userName }}
                      </div>
                      <el-tag v-for="role in userStore.userInfo.roles" :key="role.roleId" size="small" class="mt-2">
                        {{ role.roleName }}
                      </el-tag>
                    </div>
                  </div>
                  <!--                  <el-dropdown-item divided command="admin"> -->
                  <!--                    <a target="_blank" href="http://feewatch.mycrab.cn/" rel="noopener noreferrer" class="w-full"> -->
                  <!--                      <SvgIcon name="iconoir:user" class="mr-2 text-xl relative top-[5px]" /> -->
                  <!--                      后台管理 -->
                  <!--                    </a> -->
                  <!--                  </el-dropdown-item> -->
                  <el-dropdown-item divided command="logout">
                    <SvgIcon name="mdi:logout"class="mr-2 text-xl relative" />
                    <span>
                      退出登录
                    </span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <el-button
            v-else
            text
            @click="authVisible = true"
          >
            登录/注册
          </el-button>
        </div>
      </div>
    </header>
    <main class="flex-1">
      <div class="container flex items-center justify-center min-h-[calc(100vh-12rem)]">
        <div class="w-full max-w-2xl px-4 py-8 space-y-6 text-center">
          <img src="@/assets/images/search.png" alt="logo" class="w-[100px] inline-block">
          <h1 class="text-gray-700 dark:text-gray-300 text-2xl font-bold tracking-tight">
            请在下方输入专利号或者申请号进行查询！
          </h1>
          <p v-if="token" class="text-gray-500 dark:text-gray-400">
            当前账号剩余 <span class="text-orange-600">{{ queryCount }}</span> 次免费查询次数
          </p>
          <div class="flex justify-center gap-2">
            <div class="relative flex-1 max-w-[500px] flex-center flex-col">
              <el-input
                v-model.trim="searchVal"
                placeholder="请输入专利号/申请号"
                clearable
                size="large"
                class="mr-3 !h-12"
              />
              <el-button
                v-ripple
                type="primary"
                size="large"
                :disabled="searchVal === ''"
                class="!h-12 !text-[17px] mt-5 !w-[40%]"
                @click="handleQuery"
              >
                <template #icon>
                  <SvgIcon name="icon-park-outline:search" />
                </template>
                查询
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="bg-white py-6 mt-auto">
      <div class="container mx-auto px-4 text-center text-gray-600 text-sm">
        <p>Copyright © {{ nowDateInfo.year }} 芜湖咖博网络科技. All Rights Reserved</p>
      </div>
    </footer>
  </div>
  <div class="fixed right-6 bottom-6 z-40 flex flex-col space-y-3">
    <div class="relative group">
      <button
        class="w-12 h-12 bg-blue-500 text-white rounded-full shadow-lg flex items-center justify-center hover:bg-primary/90 transition-all"
      >
        <div class="w-6 h-6 flex items-center justify-center">
          <SvgIcon name="ri:wechat-line" class="text-xl" />
        </div>
      </button>
      <div
        class="
        flex-center
        flex-col
        w-45 absolute right-16 bottom-0 bg-white p-3 rounded-lg shadow-lg opacity-0 group-hover:opacity-100 transition-opacity duration-300 pointer-events-none group-hover:pointer-events-auto"
      >
        <img
          src="@/assets/images/kefu-qrcode.png"
          alt="客服二维码"
          class="w-32 h-32 object-cover"
        >
        <p class="text-center text-gray-700 font-medium mt-2">
          扫码联系客服
        </p>
      </div>
      <span
        class="absolute right-16 bg-white text-gray-800 px-3 py-1 rounded shadow-md opacity-0 group-hover:opacity-0 transition-opacity whitespace-nowrap"
      >微信客服</span>
    </div>

    <div class="relative group">
      <button
        class="w-12 h-12 bg-blue-500 text-white rounded-full shadow-lg flex items-center justify-center hover:bg-blue-600 transition-all"
      >
        <div class="w-6 h-6  flex items-center justify-center">
          <!--          <i class="ri-wechat-line" /> -->
          <SvgIcon name="ri:wechat-line" class="text-xl" />
        </div>
      </button>
      <div
        class="
        flex-center
        flex-col
        w-45 absolute right-16 bottom-0 bg-white p-3 rounded-lg shadow-lg opacity-0 group-hover:opacity-100 transition-opacity duration-300 pointer-events-none group-hover:pointer-events-auto"
      >
        <img
          src="@/assets/images/kefu-qrcode-1.png"
          alt="微信客服二维码"
          class="w-32 h-32 object-cover"
        >
        <p class="text-center text-gray-700 font-medium mt-2">
          扫码联系客服
        </p>
      </div>
      <span
        class="absolute right-16 bg-white text-gray-800 px-3 py-1 rounded shadow-md opacity-0 group-hover:opacity-0 transition-opacity whitespace-nowrap"
      >微信客服</span>
    </div>
    <BaseDialog
      v-model:visible="queryStatusVisible"
      class="w-[30%]"
      title="查询结果"
      :options="{
        showFooter: false,
      }"
      @close="resetQueryState"
    >
      <div class="flex-center flex-col">
        <div>
          <img v-if="queryStatusType === 'error'" src="@/assets/images/query-error.svg" alt="error" class="w-[100px] mb-5">
          <img v-if="queryStatusType === 'success'" src="@/assets/images/query-success.svg" alt="success" class="w-[100px] mb-5">
        </div>
        <div class="flex-center flex-col">
          <div class="text-2xl font-medium mb-4 text-gray-700 dark:text-gray-300">
            查询完毕
          </div>
          <div class="text-xl" :class="queryStatusType === 'error' ? 'text-red-600' : 'text-[var(--el-color-primary)]'">
            {{ queryMessage }}
          </div>
        </div>

        <div class="w-full flex-center">
          <el-button
            v-if="queryStatusType === 'success'"
            v-ripple
            type="primary"
            size="large"
            class="!text-[17px] mt-5 !w-[40%] !rounded-lg"
            @click="handleViewFeeDetail"
          >
            查看详情
          </el-button>
          <el-button
            v-if="queryStatusType === 'error'"
            v-ripple
            type="primary"
            size="large"
            class="!text-[17px] mt-5 !w-[40%] !rounded-lg"
            @click="resetQueryState"
          >
            关闭
          </el-button>
        </div>
      </div>
    </BaseDialog>
    <AuthModal v-model:visible="authVisible" />
    <ApplicationFeeDialog
      v-model:visible="feeVisible"
      :application-data="applicationData"
      :fee-data="feeData"
    />
  </div>
</template>

<style lang="scss" scoped>
.container{
  width: 100%;
  margin-right: auto;
  margin-left: auto;
  padding-right: 2rem;
  padding-left: 2rem;
}
</style>
